<template>
	<div class="main">
		<!-- 搜索框和导航栏容器 -->
		<div class="fixed-header">
			<!-- <div class=""> -->
			<!-- 搜索框 -->
			<div class="search-box">
				<navigator class="search-wrap" hover-class="none" url="/pages/goods/search">
					<u-search placeholder="请输入商品名称" wrap-bg-color="transparent" :bg-color="'#ececec'" :disabled="true"
						:height="30"></u-search>
				</navigator>
			</div>

			<!-- 导航标签栏 -->
			<div class="nav-tabs">
				<u-tabs :list="categories" :is-scroll="true" :current="activeCategoryIndex" :line-color="'#f56c6c'"
					@change="changeCategory"></u-tabs>
			</div>

			<div class="sort-bar" :class="{ 'sort-bar-fixed': isSticky }">
				<div class="sort-item" @click="sortByComprehensive">
					<text :class="{ active: sortType === 'comprehensive' }">综合</text>
				</div>
				<div class="sort-item" @click="sortByPrice">
					<text :class="{ active: sortType === 'price' }">价格</text>
					<text class="sort-arrow">{{ sortOrder === 'asc' ? '↑' : '↓' }}</text>
				</div>
				<!-- <div class="sort-item" @click="sortBySales">
					<text :class="{ active: sortType === 'sales' }">销量</text>
				</div> -->
				<div class="sort-item" @click="toggleViewMode">
					<u-icon :name="viewMode === 'grid' ? 'list' : 'grid'" size="20"></u-icon>
				</div>
			</div>
		</div>

		<!-- 内容区域 -->
		<div class="content-container">
			<!-- 轮播图 -->
			<!-- <div class="swiper-container">
				<uni-swiper-dot class="uni-swiper-dot-box" :info="bannerList" :current="bannerCurrent" field="content">
					<swiper class="swiper-box" :current="bannerCurrent" @change="changeBanner">
						<swiper-item v-for="(item, index) in bannerList" :key="index">
							<view class="swiper-item" @click="clickBannerItem(item)">
								<image :src="item.image" mode="aspectFill" :draggable="false" />
							</view>
						</swiper-item>
					</swiper>
				</uni-swiper-dot>
			</div> -->

			<!-- 排序选择栏 -->


			<!-- 商品列表 -->
			<div class="goods-container">
				<div :class="['goods-list', { 'list-view': viewMode === 'list' }]">
					<div v-for="(item, index) in currentGoods" :key="index" class="goods-item"
						@click="toggleSelect(index)">
						<div class="goods-image" @click="previewImage(item.pictureUrl)">
							<img :src="item.pictureUrl" alt="商品图片">
							<div class="goods-tag" v-if="item.tag">{{ item.tag }}</div>
						</div>
						<div class="goods-info">
							<p class="goods-title">{{ item.commodityName }}</p>
							<div class="goods-price-row">
								<p class="goods-price">￥{{ item.price }}</p>
								<p class="goods-unit">/{{ item.unitName }}</p>
							</div>
						</div>
						<p class="big-green-checkmark" :class="{ visible: item.count }">✔</p>
					</div>
				</div>
			</div>

			<!-- 返回顶部按钮 -->
			<u-back-top :scroll-top="scrollTop" :bottom="120" :right="20" @click="backToTop"></u-back-top>

			<!-- 底部派单按钮 -->
			<div class="dispatch-button">
				<u-button type="warning" @click="dispatchOrder">派单</u-button>
			</div>
		</div>

	</div>
</template>

<script>
	import {
		getGoodsInfo,
		selectAccountInfo,
		selectCardNumberInfo,
		addGoodsInfo
	} from '@/api/goods/goods.js'
	export default {

		data() {
			return {
				searchBackground: '#ffffff',
				searchText: '',
				currentTab: 1,
				sortType: 'comprehensive',
				sortOrder: 'desc',
				viewMode: 'list',
				bannerCurrent: 0, // 轮播图当前索引
				swiperDotIndex: 0,
				customerCode: null,
				customerName: null,
				accountId: null,
				bankAccount: null,
				params: {
					customerName: '',
					deptId: '100',
				},
				accountParams: {
					codeId: null,
				},
				//负责人
				customerCodeOption: [],
				//负责人
				accountIdOption: [],
				// 商品分类列表
				categories: [],
				// 当前激活的分类索引
				activeCategoryIndex: 0,
				// 所有商品数据
				allGoods: [],
				// 控制派单弹出页面的显示和隐藏
				isDispatchModalVisible: false,
				// 所选的户头
				selectedAccount: '',
				// 所选的商品
				selectedGoods: [],
				drivers: [{
					licensePlate: null,
					driverName: null,
					phoneNumber: null,
					idCardNumber: null,
					toDate: null
				}],
				// 轮播图数据
				/* bannerList: [{
					image: 'https://henanhanyong.oss-cn-beijing.aliyuncs.com/2025/01/11/a7bc3138-a48a-4bf8-ba3d-7fb6e72e1f90.jpg'
				},
				{
					image: 'https://henanhanyong.oss-cn-beijing.aliyuncs.com/2025/01/11/443046ef-8794-4716-99d1-3c960c103055.jpg'
				},
				{
					image: 'https://henanhanyong.oss-cn-beijing.aliyuncs.com/2025/01/11/62408c1f-4f5d-470b-a2c2-5265e700b0e6.jpg'
				}
				], */
				isSticky: false,
				scrollTop: 0,
			};
		},
		computed: {
			// 当前分类下的商品列表
			currentGoods() {
				return this.allGoods[this.activeCategoryIndex];
			},
			hasSelectedGoods() {
				return this.allGoods.some(categoryGoods =>
					categoryGoods.some(good => good.count > 0)
				);
			}
		},
		// onLoad() {
		// 	// this.selectLeader();
		// 	this.getGoodsTypeInfo();
		// },
		onShow() {
			const goodCategoryId = uni.getStorageSync('goodCategoryId');
			if (goodCategoryId !== '' || goodCategoryId === 0) {
				this.activeCategoryIndex = goodCategoryId;
				// 获取数据后可以清除存储
				uni.removeStorageSync('goodCategoryId');
			}
			this.getGoodsTypeInfo();
		},
		onPageScroll(e) {
			// 更新滚动位置
			this.scrollTop = e.scrollTop;
			// 当滚动超过一定距离时，使排序栏吸顶
			this.isSticky = e.scrollTop >= 230; // 根据实际布局调整这个值
		},
		methods: {
			getGoodsTypeInfo() {
				getGoodsInfo().then(res => {
					this.categories = res.goodsType.map(v => {
						return {
							...v,
							name: v.goodCategoryName,
						}
					})
					this.allGoods = res.goodsInfo
				})
				// this.categories = goods.goodsType
				// this.allGoods = goods.goodsInfo
				this.allGoods.forEach(v => {
					v.forEach(i => {
						this.$set(i, 'count', 0)
					})
				})
			},
			calculateTotalPrice() {
				return this.selectedGoods.reduce((total, good) => {
					return total + good.count * good.price;
				}, 0);
			},
			addDriver() {
				this.drivers.push({
					licensePlate: '',
					driverName: '',
					phoneNumber: '',
					idCardNumber: '',
					toDate: ''
				});
			},
			//选择责任人
			selectLeader(val) {
				//输入名字查询远程查询
				this.params.customerName = val;
				selectCardNumberInfo(this.params).then(resp => {
					this.customerCodeOption = resp.data;
				})
			},
			//选择银行户头
			selectAccountId() {
				this.accountParams.codeId = this.customerCode
				selectAccountInfo(this.accountParams).then(resp => {
					this.accountIdOption = resp.data;
				})
			},
			// 切换商品分类
			changeCategory({
				index
			}) {
				this.activeCategoryIndex = index;
				this.getGoodsTypeInfo();
			},
			// 切换商品选择状态
			toggleSelect(index) {
				// 判断当前点击的商品是否已经被选中
				const isSelected = this.currentGoods[index].count === 1;

				// 遍历所有分类的商品，重置选中状态
				this.allGoods.forEach(categoryGoods => {
					categoryGoods.forEach(item => {
						item.count = 0; // 重置所有商品的选中状态
					});
				});

				// 如果当前商品未被选中，则选中它；否则保持取消状态
				this.currentGoods[index].count = isSelected ? 0 : 1;
			},
			// 派单方法
			dispatchOrder() {
				let selectedGood = null;
				this.allGoods.forEach(categoryGoods => {
					categoryGoods.forEach(good => {
						if (good.count > 0) {
							selectedGood = {
								...good
							};
						}
					});
				});

				if (selectedGood == null) {
					this.$modal.msgError("必须选择一个商品");
					return;
				}
				if (selectedGood) {
					// 跳转到新页面，并传递选中的商品信息
					uni.navigateTo({
						url: `/pages/goods/dispatch?selectedGood=${JSON.stringify(selectedGood)}`
					});
				}
			},
			// 关闭派单弹出页面
			closeDispatchModal() {
				this.isDispatchModalVisible = false;
			},
			submitOrder() {
				// 收集用户信息（这里假设是客户信息）
				const userInfo = {
					customerCode: this.customerCode,
					customerName: this.customerName,
					accountId: this.accountId,
					bankAccount: this.bankAccount
				};

				// 收集司机信息
				const driverInfo = this.drivers.filter(driver => {
					return Object.values(driver).some(value => value && String(value).trim() !== '');
				});

				// 收集选中的商品信息
				const selectedGoods = this.selectedGoods.filter(good => good.count > 0);

				// 验证客户信息
				if (!userInfo.customerCode || !userInfo.accountId) {
					this.$modal.msgError("请填写完整的客户信息");
					return;
				}

				// 验证司机信息
				if (driverInfo.length === 0) {
					this.$modal.msgError("请填写至少一个司机信息");
					return;
				}

				// 验证司机信息中所有字段是否都填写
				for (const driver of driverInfo) {
					if (!driver.licensePlate || !driver.driverName || !driver.phoneNumber || !driver.idCardNumber || !
						driver.toDate) {
						this.$modal.msgError("请填写完整的司机信息");
						return;
					}
				}

				// 验证选中的商品信息
				if (selectedGoods.length === 0) {
					this.$modal.msgError("请选择至少一个商品");
					return;
				}

				const datainfo = {
					userInfo,
					driverInfo,
					selectedGoods
				};

				// 表单验证通过，提交数据
				addGoodsInfo(datainfo).then(res => {
					if (res.code === 200) {
						this.$modal.msgSuccess("添加成功");
					} else {
						this.$modal.msgError("添加失败");
					}
				});
			},
			removeGoods(index) {
				this.selectedGoods.splice(index, 1);
			},
			clickBannerItem(item) {
				console.info(item)
			},
			changeBanner(e) {
				this.bannerCurrent = e.detail.current
			},
			switchTab(index) {
				this.currentTab = index;
			},
			sortByComprehensive() {
				this.sortType = 'comprehensive';

			},
			sortByPrice() {
				this.sortType = 'price';
				this.sortOrder = this.sortOrder === 'asc' ? 'desc' : 'asc';
				this.currentGoods.sort((a, b) => {
					if (this.sortOrder === 'asc') {
						return a.price - b.price;
					} else {
						return b.price - a.price;
					}
				});
			},
			sortBySales() {
				this.sortType = 'sales';
			},
			toggleViewMode() {
				this.viewMode = this.viewMode === 'grid' ? 'list' : 'grid';
			},
			backToTop() {
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			previewImage(url) {
				uni.previewImage({
					urls: [url], // 可以是多张图片的数组
					current: url // 当前预览的图片
				});
			},
		},
	};
</script>

<style lang="scss" scoped>
	.fixed-header {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #fff;
	}

	.content-container {
		padding-top: 150px; // 增加顶部间距，为固定的搜索框和导航栏留出空间
	}

	.main {
		min-height: 100vh;
		background-color: #f5f7fa;
		padding-bottom: 60px;
	}

	.search-box {
		padding: 8px 15px;
		background-color: #ffffff;
	}

	.nav-tabs {
		background-color: #fff;
		border-bottom: 1px solid #eee;
		overflow-x: hidden;
		padding: 0; // 移除内边距

		.tab-list {
			display: flex;
			justify-content: space-around;
			padding: 0 10px;

			.tab-item {
				padding: 8px 15px; // 减小tab项的内边距
				font-size: 14px;
				position: relative;
				color: #666;
				flex: 1;
				text-align: center;

				&.active {
					color: #f56c6c;
					font-weight: 500;
				}
			}
		}
	}

	.swiper-container {
		padding: 8px 15px; // 减小轮播图容器的内边距

		.swiper-box {
			height: 150px;
			border-radius: 8px;
			overflow: hidden;

			.swiper-item {
				width: 100%;
				height: 100%;

				image {
					width: 100%;
					height: 100%;
					object-fit: cover;
				}
			}
		}
	}

	.sort-bar {
		margin: 10px 15px;
		background-color: #fff;
		border-radius: 8px;
		display: flex;
		padding: 10px 0;
		transition: all 0.3s;

		&.sort-bar-fixed {
			position: fixed;
			top: 88px; // 根据顶部固定导航的高度调整
			left: 0;
			right: 0;
			z-index: 99;
			margin: 0;
			border-radius: 0;
			box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		}

		.sort-item {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 14px;
			color: #666;

			text {
				&.active {
					color: #f56c6c;
				}
			}

			.sort-arrow {
				margin-left: 4px;
				font-size: 12px;
			}
		}
	}

	.goods-container {
		padding: 10px;

		.sort-bar-fixed+& {
			padding-top: 50px; // 根据排序栏高度调整
		}
	}

	.goods-list {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 10px;
		padding: 0 15px;

		&.list-view {
			display: block;

			.goods-item {
				display: flex;
				margin-bottom: 10px;
				background-color: #fff;
				border-radius: 8px;

				.goods-image {
					width: 120px;
					height: 120px;
					padding-top: 0;
					flex-shrink: 0;

					img {
						position: relative;
						height: 100%;
						object-fit: cover;
					}
				}

				.goods-info {
					flex: 1;
					padding: 10px;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.goods-title {
						margin-bottom: 0;
						font-weight: bold; // 添加字体加粗样式
					}

					.goods-price-row {
						margin-top: auto;
					}
				}
			}
		}
	}

	.goods-item {
		background-color: #fff;
		border-radius: 8px;
		overflow: hidden;
		position: relative;

		.goods-image {
			position: relative;
			padding-top: 100%;

			img {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.goods-tag {
				position: absolute;
				top: 8px;
				right: 8px;
				background-color: #f56c6c;
				color: #fff;
				padding: 2px 6px;
				border-radius: 4px;
				font-size: 12px;
			}
		}

		.goods-info {
			padding: 8px;

			.goods-title {
				font-size: 14px;
				color: #333;
				margin-bottom: 4px;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow: hidden;
			}

			.goods-price-row {
				display: flex;
				align-items: baseline;

				.goods-price {
					color: #f56c6c;
					font-size: 16px;
					font-weight: bold;
				}

				.goods-unit {
					color: #999;
					font-size: 12px;
					margin-left: 2px;
				}
			}
		}
	}

	.dispatch-button {
		margin-bottom: 50px;
		position: fixed;
		bottom: 30px;
		left: 0;
		right: 0;
		padding: 10px 15px;
		background-color: #fff;
		box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.1);
		z-index: 999;

		:deep(.u-button) {
			width: 100%;
		}
	}

	// 保持原有的选中对钩样式
	.big-green-checkmark {
		position: absolute;
		top: 10px;
		right: 10px;
		width: 24px;
		height: 24px;
		background-color: #1a73e8;
		color: #fff;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 14px;
		opacity: 0;
		visibility: hidden;
		transition: all 0.2s;

		&.visible {
			opacity: 1;
			visibility: visible;
		}
	}
</style>